package com.yupi.springbootinit.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.yupi.springbootinit.model.dto.chart.CsvDataDTO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author vvv
 * @date 2023-11-28 16 01
 * discription
 */
public class ExcelUtils {

    /**
     * Excel 文件 to  csv 字符串
     *
     * @param multipartFile
     * @return
     */
    public static CsvDataDTO Excel2Csv(MultipartFile multipartFile) {
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (CollectionUtils.isEmpty(list)) {
           return null;
        }
        // 1. 数据转换
        StringBuilder result = new StringBuilder();
        CsvDataDTO csvDataDTO = new CsvDataDTO();
        // 表头
        LinkedHashMap<Integer, String> headMap = (LinkedHashMap<Integer, String>) list.get(0);
        // 判空
        List<String> headList = headMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        csvDataDTO.setChartHead(headList);
        result.append(StringUtils.join(headList, ",")).append("\n");
        // 表身
        List<String> chartBody = new ArrayList<>();
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> bodyMap = (LinkedHashMap<Integer, String>) list.get(i);
            // 判空
            List<String> bodyList = bodyMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            String bodyStr = StringUtils.join(bodyList, ",");
            chartBody.add(bodyStr);
            result.append(bodyStr).append("\n");
        }
        csvDataDTO.setChartBody(chartBody);
        csvDataDTO.setCsv(result.toString());
        return csvDataDTO;
    }
}
